<template>
  <view class="work-container">
    <!-- 顶部标题和日期 -->
    <view class="header">
      <view class="title-container">
        <text class="title">工作台</text>
      </view>
      <view class="date-container">
        <text class="date">{{currentDate}}</text>
      </view>
      <view class="notification">
        <view class="notification-icon">
          <view class="badge">3</view>
          <uni-icons type="notification-filled" size="24" color="#333"></uni-icons>
        </view>
      </view>
    </view>

    <!-- 常用功能模块 -->
    <view class="section-container">
      <view class="section-header">
        <view class="section-title-container">
          <view class="section-indicator"></view>
          <text class="section-title">常用功能</text>
        </view>
        <view class="more-link">
          <text class="more-text">更多</text>
          <text class="more-icon">›</text>
        </view>
      </view>
      <view class="function-grid">
        <view class="function-item" @click="goToAttendance">
          <view class="function-icon attendance-icon">
            <uni-icons type="calendar" size="24" color="#0075ff"></uni-icons>
          </view>
          <text class="function-text">员工打卡</text>
        </view>
        <view class="function-item" @click="goToAttendanceList">
          <view class="function-icon record-icon">
            <uni-icons type="list" size="24" color="#6010be"></uni-icons>
          </view>
          <text class="function-text">打卡记录</text>
        </view>
        <view class="function-item" @click="goToReapplyPage">
          <view class="function-icon reapply-icon">
            <uni-icons type="refresh" size="24" color="#e02020"></uni-icons>
          </view>
          <text class="function-text">补卡申请</text>
        </view>
        <view class="function-item" @click="goToLeavePage">
          <view class="function-icon leave-icon">
            <uni-icons type="paperplane" size="24" color="#d4137a"></uni-icons>
          </view>
          <text class="function-text">请假申请</text>
        </view>
      </view>
    </view>

    <!-- 数据统计 -->
    <view class="section-container">
      <view class="section-header">
        <view class="section-title-container">
          <view class="section-indicator"></view>
          <text class="section-title">数据统计</text>
        </view>
        <view class="refresh-button" @click="refreshStatistics">
          <uni-icons type="refresh" size="20" color="#4080FF"></uni-icons>
        </view>
      </view>
      <view class="stats-container" v-if="!loading">
        <view class="stats-item">
          <view class="stats-header">
            <text class="stats-title">本月出勤</text>
            <uni-icons type="info" size="16" color="#999"></uni-icons>
          </view>
          <view class="stats-value-container">
            <text class="stats-value">{{statistics.attendance}}</text>
            <text class="stats-unit">天</text>
          </view>
        </view>
        <view class="stats-item">
          <view class="stats-header">
            <text class="stats-title">请假天数</text>
            <uni-icons type="info" size="16" color="#999"></uni-icons>
          </view>
          <view class="stats-value-container">
            <text class="stats-value">{{statistics.leaveCount}}</text>
            <text class="stats-unit">天</text>
          </view>
        </view>
        <view class="stats-item">
          <view class="stats-header">
            <text class="stats-title">补卡次数</text>
            <uni-icons type="info" size="16" color="#999"></uni-icons>
          </view>
          <view class="stats-value-container">
            <text class="stats-value">{{statistics.makeupCount}}</text>
            <text class="stats-unit">次</text>
          </view>
        </view>
      </view>
      <view class="stats-loading" v-else>
        <uni-icons type="spinner-cycle" size="28" color="#4080FF"></uni-icons>
        <text class="loading-text">数据加载中...</text>
      </view>
    </view>

    <!-- 系统管理模块 -->
    <view class="section-container">
      <view class="section-header">
        <view class="section-title-container">
          <view class="section-indicator"></view>
          <text class="section-title">系统管理</text>
        </view>
      </view>
      <view class="system-grid">
        <view class="system-item" v-for="(item, index) in systemModules" :key="index" @click="handleSystem(index)">
          <view class="system-icon" :class="`system-icon-${index}`">
            <uni-icons :type="item.icon" size="24" :color="iconColors[index]"></uni-icons>
          </view>
          <text class="system-text">{{item.name}}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  import request from '@/utils/request'
  
  export default {
    data() {
      return {
        systemModules: [
          { name: '用户管理', icon: 'person-filled' },
          { name: '角色管理', icon: 'staff-filled' },
          { name: '菜单管理', icon: 'list' },
          { name: '部门管理', icon: 'settings-filled' },
          { name: '岗位管理', icon: 'heart-filled' },
          { name: '字典管理', icon: 'bars' },
          { name: '参数设置', icon: 'gear-filled' },
          { name: '通知公告', icon: 'chat-filled' },
          { name: '日志管理', icon: 'wallet-filled' }
        ],
        // 图标颜色
        iconColors: [
          '#0075ff', // 用户管理 - 更深的蓝色
          '#6010be', // 角色管理 - 更深的紫色
          '#0ba3a3', // 菜单管理 - 更深的青色
          '#389e0d', // 部门管理 - 更深的绿色
          '#d48806', // 岗位管理 - 更深的黄色
          '#d46b08', // 字典管理 - 更深的橙色
          '#cf1322', // 参数设置 - 更深的红色
          '#c41d7f', // 通知公告 - 更深的粉色
          '#7cb305'  // 日志管理 - 更深的亮绿色
        ],
        // 统计数据
        statistics: {
          attendance: 0,
          leaveCount: 0,
          makeupCount: 0
        },
        loading: false,
        currentDate: ''
      }
    },
    mounted() {
      this.getStatisticsData();
      this.updateCurrentDate();
    },
    methods: {
      // 更新当前日期
      updateCurrentDate() {
        const now = new Date();
        const year = now.getFullYear();
        const month = now.getMonth() + 1;
        const day = now.getDate();
        
        // 获取星期几
        const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
        const weekday = weekdays[now.getDay()];
        
        this.currentDate = `${year}年${month}月${day}日 周${weekday}`;
      },
      
      // 获取统计数据
      getStatisticsData() {
        this.loading = true;
        console.log('开始获取统计数据...');
        
        // 这里使用Promise.all同时请求多个接口
        Promise.all([
          this.getAttendanceData(),
          this.getLeaveData(),
          this.getMakeupData()
        ]).then(([attendanceRes, leaveRes, makeupRes]) => {
          console.log('统计数据API响应:', {
            attendance: attendanceRes,
            leave: leaveRes,
            makeup: makeupRes
          });
          
          // 处理考勤数据
          if (attendanceRes && attendanceRes.code === 200) {
            this.statistics.attendance = attendanceRes.data || 0;
          }
          
          // 处理请假数据
          if (leaveRes && leaveRes.code === 200) {
            this.statistics.leaveCount = leaveRes.data || 0;
          }
          
          // 处理补卡数据
          if (makeupRes && makeupRes.code === 200) {
            this.statistics.makeupCount = makeupRes.data || 0;
          }
          
          console.log('最终统计数据:', JSON.stringify(this.statistics));
        }).catch(error => {
          console.error('获取统计数据失败:', error);
          this.$modal.showToast('获取统计数据失败，请稍后重试');
          
          // 5秒后自动重试一次
          setTimeout(() => {
            if (this.statistics.attendance === 0 && 
                this.statistics.leaveCount === 0 && 
                this.statistics.makeupCount === 0) {
              console.log('自动重试获取统计数据');
              this.getStatisticsData();
            }
          }, 5000);
        }).finally(() => {
          this.loading = false;
        });
      },
      
      // 获取考勤数据
      getAttendanceData() {
        return request({
          url: '/system/attendance/stats',
          method: 'get'
        }).then(res => {
          if (res.code === 200 && res.data) {
            // 返回正常打卡天数作为本月出勤
            return {
              code: 200,
              msg: '操作成功',
              data: res.data.normalDays || 0
            };
          }
          return {
            code: 500,
            msg: '获取考勤数据失败',
            data: 0
          };
        }).catch(error => {
          console.error('获取考勤数据失败:', error);
          return {
            code: 500,
            msg: '获取考勤数据失败',
            data: 0
          };
        });
      },
      
      // 获取请假数据
      getLeaveData() {
        // 首先尝试从leave/list接口获取数据
        return this.getLeaveDataFromList().catch(error => {
          console.log('从leave/list获取请假数据失败，尝试备用方法');
          return this.getLeaveDataFromStats();
        });
      },
      
      // 从leave/list接口获取请假数据
      getLeaveDataFromList() {
        return request({
          url: '/system/attendance/leave/list',
          method: 'get',
          params: {
            pageNum: 1,
            pageSize: 999,
            status: '1' // 已批准的请假
          }
        }).then(res => {
          if (res.code === 200) {
            console.log('请假数据原始响应(list):', JSON.stringify(res));
            
            // 计算请假天数总和
            let totalDays = 0;
            
            if (res.rows && res.rows.length > 0) {
              console.log('找到请假记录数量:', res.rows.length);
              
              res.rows.forEach(item => {
                console.log('处理请假记录:', JSON.stringify(item));
                
                // 尝试多种方式计算请假天数
                if (item.days) {
                  // 直接使用days字段
                  const days = parseFloat(item.days);
                  console.log(`使用days字段: ${days}天`);
                  totalDays += days;
                } else if (item.beginTime && item.endTime) {
                  // 计算开始和结束日期之间的天数
                  try {
                    const beginDate = new Date(item.beginTime);
                    const endDate = new Date(item.endTime);
                    const diffTime = Math.abs(endDate - beginDate);
                    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
                    console.log(`计算日期差: ${diffDays}天`);
                    totalDays += diffDays;
                  } catch (e) {
                    console.error('日期计算错误:', e);
                  }
                } else if (item.duration) {
                  // 使用duration字段
                  const duration = parseFloat(item.duration);
                  console.log(`使用duration字段: ${duration}天`);
                  totalDays += duration;
                }
              });
              
              console.log('计算的总请假天数:', totalDays);
            }
            
            // 如果通过API计算的天数为0，但有请假记录，则至少显示1天
            if (totalDays === 0 && res.rows && res.rows.length > 0) {
              console.log('请假天数为0但有记录，设置为记录数量');
              totalDays = res.rows.length;
            }
            
            return {
              code: 200,
              msg: '操作成功',
              data: totalDays
            };
          }
          return Promise.reject('获取请假数据失败');
        });
      },
      
      // 从stats接口获取请假数据
      getLeaveDataFromStats() {
        return request({
          url: '/system/attendance/stats',
          method: 'get'
        }).then(res => {
          if (res.code === 200 && res.data) {
            console.log('从统计接口获取请假数据:', JSON.stringify(res.data));
            
            // 尝试从统计数据中获取请假天数
            let leaveDays = 0;
            
            // 检查各种可能的字段名
            if (res.data.leaveDays !== undefined) {
              leaveDays = res.data.leaveDays;
            } else if (res.data.leaveCount !== undefined) {
              leaveDays = res.data.leaveCount;
            } else if (res.data.leaveTotal !== undefined) {
              leaveDays = res.data.leaveTotal;
            } else if (res.data.absentDays !== undefined) {
              // 可能请假记录在缺勤天数中
              leaveDays = res.data.absentDays;
            }
            
            console.log('从统计接口获取的请假天数:', leaveDays);
            
            return {
              code: 200,
              msg: '操作成功',
              data: leaveDays
            };
          }
          return {
            code: 500,
            msg: '获取请假数据失败',
            data: 0
          };
        }).catch(error => {
          console.error('从统计接口获取请假数据失败:', error);
          return {
            code: 500,
            msg: '获取请假数据失败',
            data: 0
          };
        });
      },
      
      // 获取补卡数据
      getMakeupData() {
        return request({
          url: '/system/attendance/reapply/list',
          method: 'get',
          params: {
            pageNum: 1,
            pageSize: 999,
            status: '1', // 已批准的补卡
            type: 'reapply' // 明确指定类型为补卡
          }
        }).then(res => {
          if (res.code === 200) {
            console.log('补卡数据原始响应:', JSON.stringify(res));
            
            // 确保只统计补卡记录，不包括请假记录
            let reapplyCount = 0;
            
            if (res.rows && res.rows.length > 0) {
              // 过滤出真正的补卡记录
              const reapplyRecords = res.rows.filter(item => 
                item.type === 'reapply' || // 类型为补卡
                item.reapplyType || // 有补卡类型字段
                (item.remark && item.remark.includes('补卡')) // 备注中包含"补卡"
              );
              
              reapplyCount = reapplyRecords.length;
              console.log('过滤后的补卡记录数:', reapplyCount);
            } else {
              reapplyCount = res.total || 0;
            }
            
            return {
              code: 200,
              msg: '操作成功',
              data: reapplyCount
            };
          }
          return {
            code: 500,
            msg: '获取补卡数据失败',
            data: 0
          };
        }).catch(error => {
          console.error('获取补卡数据失败:', error);
          return {
            code: 500,
            msg: '获取补卡数据失败',
            data: 0
          };
        });
      },
      
      // 获取模块名称
      getModuleName(index) {
        return this.systemModules[index]?.name || '未知模块';
      },
      // 跳转到指定模块
      handleSystem(index) {
        const routes = [
          '/pages/system/user/index',   // 用户管理
          '/pages/system/role/index',   // 角色管理
          '/pages/system/menu/index',   // 菜单管理
          '/pages/system/dept/index',   // 部门管理
          '/pages/system/post/index',   // 岗位管理
          '/pages/system/dict/index',   // 字典管理
          '/pages/system/config/index', // 参数设置
          '/pages/system/notice/index', // 通知公告
          '/pages/system/log/index'     // 日志管理
        ];

        if (index >= 0 && index < routes.length) {
          const targetRoute = routes[index];
          const moduleName = this.getModuleName(index);
          console.log(`准备导航到${moduleName}:`, targetRoute);
          
          uni.navigateTo({
            url: targetRoute,
            success: () => {
              console.log(`成功导航到${moduleName}:`, targetRoute);
            },
            fail: (err) => {
              console.error(`导航到${moduleName}失败:`, err);
              this.$modal.showToast(`${moduleName}模块正在开发中~`);
            }
          });
        } else {
          this.$modal.showToast('模块正在建设中~');
        }
      },
      // 跳转到打卡页面
      goToAttendance() {
        uni.navigateTo({
          url: '/pages/system/attendance/index',
          success: () => {
            console.log('成功导航到员工打卡页面');
          },
          fail: (err) => {
            console.error('导航到员工打卡页面失败:', err);
            this.$modal.showToast('打卡功能正在开发中~');
          }
        });
      },
      // 跳转到打卡记录页面
      goToAttendanceList() {
        uni.navigateTo({
          url: '/pages/system/attendance/list',
          success: () => {
            console.log('成功导航到打卡记录页面');
          },
          fail: (err) => {
            console.error('导航到打卡记录页面失败:', err);
            this.$modal.showToast('打卡记录功能正在开发中~');
          }
        });
      },
      // 跳转到补卡申请页面
      goToReapplyPage() {
        uni.navigateTo({
          url: '/pages/system/attendance/reapply',
          success: () => {
            console.log('成功导航到补卡申请页面');
          },
          fail: (err) => {
            console.error('导航到补卡申请页面失败:', err);
            this.$modal.showToast('补卡申请功能正在开发中~');
          }
        });
      },
      // 跳转到请假申请页面
      goToLeavePage() {
        uni.navigateTo({
          url: '/pages/system/attendance/leave',
          success: () => {
            console.log('成功导航到请假申请页面');
          },
          fail: (err) => {
            console.error('导航到请假申请页面失败:', err);
            this.$modal.showToast('请假申请功能正在开发中~');
          }
        });
      },
      // 跳转到模块建设中页面
      goToBuilding(pageName) {
        uni.navigateTo({
          url: '/pages/system/common/building?pageName=' + encodeURIComponent(pageName)
        });
      },
      // 刷新统计数据
      refreshStatistics() {
        this.getStatisticsData();
      }
    }
  }
</script>

<style lang="scss" scoped>
  page {
    background-color: #f7f8fa;
    min-height: 100%;
    height: auto;
  }

  .work-container {
    padding-bottom: 20px;
  }

  /* 顶部标题和日期 */
  .header {
    display: flex;
    align-items: center;
    padding: 15px 20px;
    position: relative;
  }

  .title-container {
    flex: 1;
  }

  .title {
    font-size: 18px;
    font-weight: bold;
    color: #333;
  }

  .date-container {
    margin-right: 15px;
  }

  .date {
    font-size: 14px;
    color: #666;
  }

  .notification {
    position: relative;
  }

  .notification-icon {
    position: relative;
  }

  .badge {
    position: absolute;
    top: -5px;
    right: -5px;
    background-color: #ff4d4f;
    color: white;
    font-size: 12px;
    min-width: 16px;
    height: 16px;
    line-height: 16px;
    text-align: center;
    border-radius: 8px;
    z-index: 1;
  }

  /* 功能模块共用样式 */
  .section-container {
    background-color: #fff;
    border-radius: 10px;
    margin: 0 15px 15px;
    padding: 15px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.03);
  }

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
  }

  .section-title-container {
    display: flex;
    align-items: center;
  }

  .section-indicator {
    width: 3px;
    height: 15px;
    background-color: #409EFF;
    border-radius: 1.5px;
    margin-right: 8px;
  }

  .section-title {
    font-size: 16px;
    font-weight: bold;
    color: #333;
  }

  .more-link {
    display: flex;
    align-items: center;
    color: #666;
  }

  .more-text {
    font-size: 14px;
  }

  .more-icon {
    font-size: 16px;
    margin-left: 2px;
  }

  /* 常用功能模块 */
  .function-grid {
    display: flex;
    flex-wrap: wrap;
  }

  .function-item {
    width: 25%;
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 10px;
  }

  .function-icon {
    width: 50px;
    height: 50px;
    border-radius: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 8px;
    background-color: transparent;
  }

  .attendance-icon {
    background-color: transparent;
    
    .uni-icons {
      color: #0075ff !important;
    }
  }

  .record-icon {
    background-color: transparent;
    
    .uni-icons {
      color: #6010be !important;
    }
  }

  .reapply-icon {
    background-color: transparent;
    
    .uni-icons {
      color: #e02020 !important;
    }
  }

  .leave-icon {
    background-color: transparent;
    
    .uni-icons {
      color: #d4137a !important;
    }
  }

  .function-text {
    font-size: 13px;
    color: #333;
  }

  /* 数据统计模块 */
  .stats-container {
    display: flex;
    justify-content: space-between;
  }

  .stats-item {
    flex: 1;
    background-color: #f9fafc;
    border-radius: 8px;
    padding: 12px;
    margin: 0 5px;
    
    &:first-child {
      margin-left: 0;
    }
    
    &:last-child {
      margin-right: 0;
    }
  }

  .stats-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }

  .stats-title {
    font-size: 14px;
    color: #666;
  }

  .stats-value-container {
    display: flex;
    align-items: flex-end;
  }

  .stats-value {
    font-size: 24px;
    font-weight: bold;
    color: #409EFF;
  }

  .stats-unit {
    font-size: 12px;
    color: #999;
    margin-left: 3px;
    margin-bottom: 3px;
  }

  .stats-loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px 0;
  }

  .loading-text {
    font-size: 14px;
    color: #999;
    margin-top: 10px;
  }

  .refresh-button {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 28px;
    height: 28px;
    border-radius: 50%;
    background-color: rgba(64, 158, 255, 0.1);
  }
  
  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }
  
  :deep(.uni-icons-spinner-cycle) {
    animation: spin 1s linear infinite;
  }

  /* 系统管理模块 */
  .system-grid {
    display: flex;
    flex-wrap: wrap;
  }

  .system-item {
    width: 33.33%;
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 15px;
  }

  .system-icon {
    width: 50px;
    height: 50px;
    border-radius: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 8px;
    background-color: transparent;
  }

  .system-text {
    font-size: 13px;
    color: #333;
  }

  .system-icon-0 { background-color: transparent; }
  .system-icon-1 { background-color: transparent; }
  .system-icon-2 { background-color: transparent; }
  .system-icon-3 { background-color: transparent; }
  .system-icon-4 { background-color: transparent; }
  .system-icon-5 { background-color: transparent; }
  .system-icon-6 { background-color: transparent; }
  .system-icon-7 { background-color: transparent; }
  .system-icon-8 { background-color: transparent; }
  
  .system-icon-0 .uni-icons { color: #1890ff; }
  .system-icon-1 .uni-icons { color: #722ed1; }
  .system-icon-2 .uni-icons { color: #13c2c2; }
  .system-icon-3 .uni-icons { color: #52c41a; }
  .system-icon-4 .uni-icons { color: #faad14; }
  .system-icon-5 .uni-icons { color: #fa8c16; }
  .system-icon-6 .uni-icons { color: #f5222d; }
  .system-icon-7 .uni-icons { color: #eb2f96; }
  .system-icon-8 .uni-icons { color: #a0d911; }
</style>
